package com.kc.sjwh.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kc.sjwh.dao.AppDao;
import com.kc.sjwh.dao.RoleResDao;
import com.kc.sjwh.dao.RoleUserDao;
import com.kc.sjwh.entity.po.App;
import com.kc.sjwh.other.Page;
import com.kc.sjwh.other.QueryParam;
import com.kc.sjwh.other.Tool;

/**
 * 应用service
 * @author zhangguihua(hua7381@163.com)
 * date: 2017年8月4日
 */
@Service
public class AppService {
	static Logger logger = Logger.getLogger(AppService.class);
	@Autowired
	AppDao appDao;
	@Autowired
	RoleResDao roleResDao;
	@Autowired
	RoleUserDao roleUserDao;

	public Page<App> getPage(int pageSize, int pageNum, Map<String, String> param) {
		QueryParam q = new QueryParam(pageSize, pageNum).setOrder("cjsj desc, id");
		
		//添加动态的查询条件
		String v = null;
		v = param.get("keyword");
		if(StringUtils.isNotEmpty(v)) {
			q.addSqlCondition("mc like ? or dm like ?".replace("?", "'%"+v+"%'"));
		}
		v = param.get("kssj");
		if(StringUtils.isNotEmpty(v)) {
			q.addCondition("cjsj", ">=", Tool.parseDate(v));
		}
		v = param.get("jssj");
		if(StringUtils.isNotEmpty(v)) {
			q.addCondition("cjsj", "<=", Tool.parseDate(v));
		}
		
		return appDao.getPage("get", q);
	}

	public App load4Update(String id) {
		App one = appDao.getOne(new QueryParam().put("id", id));
		return one;
	}

	public void add(App one) {
		if(appDao.getOne(new QueryParam().put("dm", one.getDm())) != null) {
			throw new IllegalArgumentException("应用代码"+one.getDm()+"已存在");
		}
		one.setId(Tool.getUuid());
		one.setCjsj(new Date());
		appDao.add(one);
	}

	public void update(App one) {
		if(one.getDm() != null && appDao.getOne(new QueryParam().put("dm", one.getDm())) != null) {
			throw new IllegalArgumentException("应用代码"+one.getDm()+"已存在");
		}
		one.setGxsj(new Date());
		appDao.update(one, "id");
	}

	@Transactional
	public void delete(String id) {
		int n = appDao.delete(id);
		if(n == 0) {
			throw new IllegalArgumentException("要删除的记录不存在");
		}
		
		//级联删除
		roleUserDao.deleteByYyid(id);
		roleResDao.deleteByYyid(id);
	}

	public List<App> getAll() {
		return appDao.getList(new QueryParam());
	}
	
	public List<App> getList(QueryParam p) {
		return appDao.getList(p);
	}
}
